package com.cskaoyan.order.exception;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.List;

/**
 * 统一异常处理、数据预处理等
 */
@ControllerAdvice(basePackages = "com.cskaoyan.order.controller")
public class ControllerExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    /**
     * 所有异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData exceptionHandler(Exception e) {

        LOG.error("系统异常：", e);
        return new ResponseUtil().setErrorMsg("系统出现异常，请联系管理员");
    }

    @ExceptionHandler(value = ValidateException.class)
    @ResponseBody
    public ResponseData handle(ValidateException e) {
        LOG.error("业务方法参数校验失败：", e);
        return new ResponseUtil().setErrorMsg(e.getMessage());
    }

    /**
     * 所有自定义异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResponseData handle(BizException e) {
        LOG.error("业务异常：", e);
        return new ResponseUtil().setErrorMsg(e.getMessage());
    }

    /**
     * 客户端请求参数校验不通过
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public ResponseData handle(ConstraintViolationException e) {
        LOG.error("[客户端请求参数校验不通过]", e);
        Iterator<ConstraintViolation<?>> it = e.getConstraintViolations().iterator();
        return new ResponseUtil().setErrorMsg("客户端请求参数校验不通过");
    }


    /**
     *  客户端请求体JSON格式错误或字段类型不匹配
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public ResponseData handle(HttpMessageNotReadableException e) {
        LOG.error("[客户端请求体JSON格式错误或字段类型不匹配]", e);
        return new ResponseUtil().setErrorMsg("客户端请求体JSON格式错误或字段类型不匹配");
    }


    /**
     * 客户端请求体参数校验不通过, 请求参数或者Json字段不满足校验规则
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class )
    @ResponseBody
    public ResponseData handle(MethodArgumentNotValidException e) {
        LOG.error("[客户端请求体参数校验不通过]", e);
        String errorMsg = this.handle(e.getBindingResult().getFieldErrors());
        return new ResponseUtil().setErrorMsg("客户端请求体参数校验不通过: " + errorMsg);
    }

    /**
     * 客户端请求体参数校验不通过, 请求参数或者Json字段不满足校验规则
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class} )
    @ResponseBody
    public ResponseData handle(BindException e) {
        LOG.error("[客户端请求体参数校验不通过]", e);
        String errorMsg = this.handle(e.getBindingResult().getFieldErrors());
        return new ResponseUtil().setErrorMsg("客户端请求体参数校验不通过: " + errorMsg);
    }

    private String handle(List<FieldError> fieldErrors) {
        StringBuilder sb = new StringBuilder();
        for (FieldError obj : fieldErrors) {
            sb.append(obj.getField());
            sb.append("=[");
            sb.append(obj.getDefaultMessage());
            sb.append("]  ");
        }
        return sb.toString();
    }
}
